
import { hex_md5 } from './md5'

function generateSign(contents) {
    contents.sort();
    let string = contents.join("");
    return hex_md5(string).toUpperCase();
}

export function login(options) {
    options = {
        tenantName: getApp().globalData.tn,
        subscriptionId: getApp().globalData.sId,
        appKey: getApp().globalData.appKey,
        appSecret: getApp().globalData.appSecret,
        softLogin: true,
        ...options
    };

    let timeStamp = new Date().getTime();
    let appKey = options.appKey;
    let appSecret = options.appSecret;
    let array = [timeStamp, appKey, appSecret, "1.0"];
    let sign = generateSign(array);

    // 请求拾果相关配置信息
    wx.request({
        url: `https://api.leshiguang.com/api/sessions/v1.0/associatedBusiness/loginTenant?api_appKey=${appKey}&api_sign=${sign}&api_timestamp=${timeStamp}&api_version=1.0`,
        data: options,
        header: {
            'Content-Type': 'application/json',
        },
        timeout: 5000,
        method: 'POST',
        withCredentials: false,
        success(response) {
            if (response.statusCode === 200) {
                if (response.data.code === 200) {
                    let { accessToken, userId } = response.data.data;
                    // 设置到globalData中
                    getApp().globalData.lsUserId = userId;
                    getApp().globalData.lsAccessToken = accessToken;
                    // 顾问绑定逻辑
                    // bindInviter()
                } else {
                    options.fail && options.fail(response.data.msg)
                }
            } else {
                options.fail && options.fail('网络异常');
            }
        },
        fail(res) {
            options.fail && options.fail(res);
        }
    })
}

export function updateUserInfo(userInfo) {
    let timeStamp = new Date().getTime();
    let appKey = getApp().globalData.appKey;
    let appSecret = getApp().globalData.appSecret;
    let array = [timeStamp, appKey, appSecret, "1.0"];
    let sign = generateSign(array);
    const options = {
        name: userInfo.nickName,
        headImage: userInfo.avatarUrl,
        sex: userInfo.sex,
        birthday: new Date(userInfo.birthday).getTime(),
        height: userInfo.height,
        waist: userInfo.waist,
    }
    // 请求拾果相关配置信息
    wx.request({
        url: `https://api.leshiguang.com/api/user/v1.0/userInfo/updateUserDetail?api_appKey=${appKey}&api_sign=${sign}&api_timestamp=${timeStamp}&api_version=1.0&associatedId=${userInfo.userId}&accessToken=${getApp().globalData.lsAccessToken}`,
        data: options,
        header: {
            'Content-Type': 'application/json',
        },
        timeout: 30000,
        method: 'POST',
        withCredentials: true,
        success(response) {
        },
        fail(res) {
        }
    })
}

const createURLParams = (url) => {
    let time = new Date().getTime();
    let params = `subscriptionId=${getApp().globalData.sId}&accessToken=${getApp().globalData.lsAccessToken}&requestId=${time}`
    return `${url.indexOf("?") >= 0 ? '&' : '?'}${params}`;
}

const createRequest = (method, url, data, load, needReLogin) => {
    if (load) {
        uni.showLoading({
            title: '请稍候',
            mask: true
        });
    }
    const baseURL = 'https://api-r7.leshiguang.com';
    const requestGetPram = createURLParams(url);
    return new Promise((resolve, reject) => {
        wx.request({
            url: url.trim().substring(0, 4) === 'http' ? `${url}${requestGetPram}` : `${baseURL}${url}${requestGetPram}`,
            data,
            header: {
                'Content-Type': 'application/json',
            },
            timeout: 30000,
            method,
            sslVerify: false,
            withCredentials: true,
            success: (response) => {
                if (load) {
                    uni.hideLoading();
                }
                if (response.statusCode === 200) {
                    if (response?.data?.code === 200) {
                        resolve(response.data);
                    } else {
                        if (response?.data?.code === 401 && needReLogin) {
                            // 判断是否需要重新登录
                            login({
                                associatedId: getApp().globalData.associatedId,
                                // userName: userInfo.nickName,
                                // headImg: userInfo.avatar,
                                // sex: userInfo.gender,
                                // env: getApp().globalData.env,
                                success: () => { },
                                fail: () => { }
                            });
                        }
                        if (load) {
                            let msg = response?.data?.msg || '';
                            uni.showToast({
                                title: msg,
                                icon: 'none',
                                duration: 2000
                            });
                        }
                        reject(response.data);
                    }
                } else {
                    if (load) {

                        let msg = response?.data?.msg || response?.data || '';
                        uni.showToast({
                            title: msg,
                            icon: 'none',
                            duration: 2000
                        });
                    }
                    reject(response.data);
                }
            },
            fail(err) {
                if (load) {
                    uni.hideLoading();
                    uni.showToast({
                        title: err.msg || err,
                        icon: 'none',
                        duration: 2000
                    });
                }

                console.error(err.msg || err);
                reject('网络异常');
            },
        });
    });
};

export function get(url, params, load, needReLogin = true) {
    return createRequest('GET', url, params, load, needReLogin);
}

export function post(url, params, load, needReLogin = true) {
    return createRequest('POST', url, params, load, needReLogin);
}
